package demo;

import pojo.City;
import pojo.Province;
import pojo.ResultVO;
import util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 02-jackson基本使用
 * ①将javabean对象转换为json字符串
 */
public class Demo03 {

    //String jsonStr = "{"provinceId":1,"provinceName":"湖北省","cityList":[{"cityid":11,"cityName":"武汉市"},{"cityid":12,"cityName":"孝感市"}]}";
    public static void main(String[] args) throws JsonProcessingException {
        //①将javabean对象转换为json字符串
        Province province = new Province();
        province.setProvinceId(1);
        province.setProvinceName("湖北省");
        List<City> cityList = new ArrayList<>();
        cityList.add(new City(11, "武汉市"));
        cityList.add(new City(12, "孝感市"));
        province.setCityList(cityList);
        String jsonStr = JsonUtils.javaBean2JsonStr(province);
        System.out.println("jsonStr = " + jsonStr);

        //②将list对象转换为json字符串
        List<Province> provinceList = new ArrayList<>();
        Province province2 = new Province();
        province2.setProvinceId(2);
        province2.setProvinceName("湖南省");
        List<City> cityList2 = new ArrayList<>();
        cityList2.add(new City(21, "长沙市"));
        cityList2.add(new City(22, "株洲市"));
        province2.setCityList(cityList2);
        provinceList.add(province);
        provinceList.add(province2);

        String jsonStr2 = JsonUtils.javaBean2JsonStr(provinceList);
        System.out.println("jsonStr2 = " + jsonStr2);

        //③将map对象转换为json字符串
        Map<String, Object> map = new HashMap<>();
        map.put("flag", true);
        map.put("msg", "添加用户成功!");
        map.put("data", null);
        String jsonStr3 = JsonUtils.javaBean2JsonStr(map);
        System.out.println("jsonStr3 = " + jsonStr3);

        //④将ResultVO对象转换为json字符串
        ResultVO<List<Province>> resultVO = new ResultVO<>();
        resultVO.setFlag(true);
        resultVO.setMsg("查询省份成功!");
        resultVO.setData(provinceList);
        String jsonStr4 = JsonUtils.javaBean2JsonStr(resultVO);
        System.out.println("jsonStr4 = " + jsonStr4);

    }

}
